package com.whut.cristiano.autographbook.Util;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.whut.cristiano.autographbook.Model.HandlePictureListener;
import com.whut.cristiano.autographbook.Model.UploadPhotoBean;
import com.whut.cristiano.autographbook.MyApplication;

import java.text.SimpleDateFormat;

/**
 * Created by ykbboom on 2017/3/7 14:31
 * email：ykbpro@whut.edu.cn
 */

public class OSSUtil extends AsyncTask<Object,Void,Boolean> {
    private static final String END_POINT = "http://oss-cn-hangzhou.aliyuncs.com";
    private static final String ACCESS_KEY = "*******";
    private static final String ACCESS_SECRET = "*******";
    private static final String BUCKET_NAME = "autographbook";
    private static final String TAG = "OSSUtil";

    private OSSCredentialProvider ossCredentialProvider;
    private ClientConfiguration clientConfiguration;
    private OSS oss;
    private Context mContext;
    private boolean isUploaded;
    private int flag = 0;
    private ProgressDialog progressDialog;
    private HandlePictureListener handlePictureListener;
    private String picUrl;
    private String time;

    public OSSUtil(ProgressDialog progressDialog, HandlePictureListener handlePictureListener){
        this.ossCredentialProvider = new OSSPlainTextAKSKCredentialProvider(ACCESS_KEY,ACCESS_SECRET);
        this.clientConfiguration = getClientConfiguration();
        mContext = MyApplication.getContext();
        this.progressDialog = progressDialog;
        this.handlePictureListener = handlePictureListener;
    }

    @Override
    protected void onPreExecute() {
        showDialog(progressDialog);
    }

    @Override
    protected Boolean doInBackground(Object... params) {
        UploadPhotoBean uploadPhotoBean = (UploadPhotoBean) params[0];
        while(true){
            if (flag==0){
                this.uploadPhoto(uploadPhotoBean.getImageName(),uploadPhotoBean.getImageUrl());
                flag = 3;//临时值
            }if (flag==1||flag==2){
                break;
            }
        }
        if (isUploaded&&flag!=0){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            time = simpleDateFormat.format(new java.util.Date());
            LogUtil.i(TAG,"当前时间:"+time);
            picUrl = "http://autographbook.oss-cn-hangzhou.aliyuncs.com/"+uploadPhotoBean.getImageName();
            return true;
        }else {
            return false;
        }
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        if (aBoolean){
            handlePictureListener.onStop(picUrl,isUploaded,time);
            ToastUtil.showToast(mContext,"上传图片成功");
        }else {
            progressDialog.dismiss();
            ToastUtil.showToast(mContext,"上传图片失败,请检查网络");
        }
    }

    public ClientConfiguration getClientConfiguration(){
        clientConfiguration = new ClientConfiguration();
        clientConfiguration.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        clientConfiguration.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        clientConfiguration.setMaxConcurrentRequest(5); // 最大并发请求数，默认5个
        clientConfiguration.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        return clientConfiguration;
    }
    public OSS getOSS(){
        oss = new OSSClient(mContext, END_POINT, ossCredentialProvider, clientConfiguration);
        return oss;
    }
    /**
     * 上传图片
     * */
    public void uploadPhoto(String objKey, String uploadPath){
        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(BUCKET_NAME, objKey, uploadPath);
        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                LogUtil.d(TAG, "当前进度: " + currentSize + " 总进度: " + totalSize);
            }
        });
        OSSAsyncTask task = getOSS().asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                LogUtil.d(TAG,"上传成功/"+"ETag:"+result.getETag()+"/RequestId:"+result.getRequestId());
                isUploaded = true;
                flag = 1;//成功
            }
            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                    isUploaded = false;
                    flag = 2;//错误
                }
                if (serviceException != null) {
                    // 服务异常
                    LogUtil.e(TAG,"ErrorCode:"+serviceException.getErrorCode());
                    LogUtil.e(TAG,"RequestId:"+serviceException.getRequestId());
                    LogUtil.e(TAG,"HostId:"+serviceException.getHostId());
                    LogUtil.e(TAG,"RawMessage:"+serviceException.getRawMessage());
                    isUploaded = false;
                    flag = 2;//错误
                }
            }
        });
        // task.cancel(); // 可以取消任务
        // task.waitUntilFinished(); // 可以等待任务完成
    }
    public void showDialog(ProgressDialog progressDialog) {
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
        progressDialog.setMessage("正在上传纪念卡...");
        progressDialog.show();
    }
}
